<template>
  <!--物流信息	-->
  <div>
    <FilterTable height="auto" ref="tableInfo" :columns="columns" :isSelectColumn="isSelectColumn" selectionType="single" :isMemoryPagination="true" :onSyncTableData="syncFun" :datakey="'records'" :isToperInfo="false" :onColumnsChange="columns => (this.columns = columns)" columnsRef="notification_maintain_info_02">

      <template slot="controls">
        <el-button v-show="formType == 'add' || formType == 'edit'" size="small" type="primary" icon="el-icon-plus" @click="addFun()">新增</el-button>
      </template>
    </FilterTable>
  </div>
</template>

<script>
import { dictionary } from '@/utils/dictMixin';
import * as types from '@/api/cms-api/origin/originInfo/types';
import { phoneAndSolidify, email } from '@/utils/validate.js';
import vm from './bridge';

export default {
  mixins: [dictionary],
  model: {
    prop: 'pdata',
    event: 'click'
  },
  props: {
    pdata: {
      type: Object,
      default: () => ({})
    },
    formType: {
      type: String,
      required: true
    },
    formOptions: {
      type: Object,
      required: true
    }
  },
  data() {
    return {
      columns: this.createColumns(),
      isSelectColumn: false,
      saveData: {
        editType: '',
        xxList: []
      },
      provinceList: [],
      cityList: [],
      districtList: []
    };
  },
  mounted() {
    //注册经销商类型变化时触发的事件
    // this.initProvince();
  },
  methods: {
    //初始化数据
    init(data) {
      let pdataCopy = JSON.parse(JSON.stringify(this.pdata));
      this.$refs.tableInfo.SET_TABLE_DATA(pdataCopy.logisticsList);
    },
    //表单验证通过后
    formChangeHandle(val) {
      this.pdata = Object.assign(this.pdata, val);
      //传递数据到父组件里
      this.$emit('click', this.pdata);
      //触发外部的事件，以标志着本表单已经准备完毕
      // this.$emit('formchange', this.pdata);
    },
    //开放的提交方法
    saveDialog() {
      let flag = true;
      const err = this.$refs.tableInfo.GET_REQUIRED_ERROR() // 非空的判断
      const error = this.$refs.tableInfo.GET_FORMAT_ERROR() // 正则的判断
      if (err || error) {
        this.saveData.xxList.forEach(item =>{
          if (item.cityId==''|| item.districtId=='' || item.provinceId==''){
            this.$notify.error({ title: '提示信息', message:'省市区不能为空!' });
          }
        })

        flag = false;
      }
      return flag;
    },
    //搜索数据
    createColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.$index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 50,
          fixed: 'left',
          render: (props, h) => {
            return (
              <div>
                <el-button v-show={this.formType == 'add' || this.formType == 'edit'} size="mini" type="text" onClick={() => this.deleteRow(props.row, props.$index)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '类型',
          dataIndex: 'addressType',
          filterType: 'input',
          sorter: true,
          filter: true,
          editable: true,
          showOverflowTooltip: true,
          editRequired: this.formType == 'add' || this.formType == 'edit',
          editType: 'select',
          editItems: this.createDictList('1726'),
          dictItems: this.createDictList('1726'),
          editValidator: (value, row, callback) => {
            if (value === undefined || value === '' || value === null) {
              callback(new Error("必填字段"));
            }
          }
        },
        {
          title: '地址简称',
          dataIndex: 'addressOr',
          filterType: 'input',
          sorter: true,
          editable: true,
          editRequired: true,
          msgtitle:'请输入',
          maxlength: 30,
        },
        {
          title: '省份',
          dataIndex: 'provinceId',
          editType: 'select',
          filterType: 'input',
          filter: true,
          editable: true,
          showOverflowTooltip: false,
          editRequired: this.formType == 'add' || this.formType == 'edit',
          dictItems: this.createRegionList(),
          editItems: this.createRegionList(),
          width: 120,
          editValidator: (value, row, callback) => {
            if (value === undefined || value === '' || value === null) {
              callback(new Error("必填字段"));
            }
          },
          disabled: this.formType === 'show' ? true : false,
          render: props => {
            return <div>
              <el-select v-model={props.row.provinceId} onChange={this.initCity(props.row.provinceId)} clearable={true} placeholder="请选择">
                {this.createRegionList().map((item) => (
                  <el-option key={item.value} label={item.text} value={item.value} />
                ))}
              </el-select>
            </div>;
          }
        },
        {
          title: '城市',
          dataIndex: 'cityId',
          editType: 'select',
          filter: true,
          filterType: 'input',
          editable: true,
          showOverflowTooltip: false,
          editRequired: this.formType == 'add' || this.formType == 'edit',
          dictItems: [],
          editItems: [],
          initialValue:'',
          width: 120,
          disabled: this.formType === 'show' ? true : false,
          editValidator: (value, row, callback) => {
            if (value === undefined || value === '' || value === null) {
              callback(new Error("必填字段"));
            }
          },
          render: props => {
            let cityData =this.createcityList(props.row.provinceId)
            let flag = false
            cityData.forEach(item =>{
              if (item.value == props.row.cityId){
                flag = true
                return ;
              }
            })
            if (!flag){
              props.row.cityId = ''
              props.row.districtId = ''
            }
            return <div>
              <el-select v-model={props.row.cityId} placeholder="请选择">
                {this.createcityList(props.row.provinceId).map((item) => (
                  <el-option key={item.value} label={item.text} value={item.value} />
                ))}
              </el-select>
            </div>;
          }
        },
        {
          title: '区县',
          dataIndex: 'districtId',
          editType: 'select',
          filter: true,
          editable: true,
          filterType: 'input',
          editRequired: false,
          showOverflowTooltip: false,
          dictItems: [],
          editItems: [],
          initialValue:'',
          width: 120,
          disabled: this.formType === 'show' ? true : false,
          editValidator: (value, row, callback) => {
            if (value === undefined || value === '' || value === null) {
              callback(new Error("必填字段"));
            }
          },
          render: props => {
            let districtData =this.district(props.row.cityId)
            let flag = false
            districtData.forEach(item =>{
              if (item.value == props.row.districtId){
                flag = true
                return ;
              }
            })
            if (!flag){
              props.row.districtId = ''
            }
            return <div>
              <el-select v-model={props.row.districtId} placeholder="请选择">
                {this.district(props.row.cityId).map((item) => (
                  <el-option key={item.value} label={item.text} value={item.value} />
                ))}
              </el-select>
            </div>;
          }
        },
        {
          title: '详细地址',
          dataIndex: 'address',
          filterType: 'input',
          sorter: true,
          editable: true,
          editRequired: true,
          maxlength: 100,
          msgtitle:'请输入',
          editValidator: (value, row, callback) => {
            if (value === undefined || value === '' || value === null) {
              callback(new Error("必填字段"));
            }
          }
        },
        {
          title: '联系人',
          dataIndex: 'linkMan',
          filterType: 'input',
          sorter: true,
          editable: true,
          editRequired: true,
          maxlength: 20,
          msgtitle:'请输入',
          editValidator: (value, row, callback) => {
            if (value === undefined || value === '' || value === null) {
              callback(new Error("必填字段"));
            }
          }
        },
        {
          title: '联系方式',
          dataIndex: 'linkPhone',
          filterType: 'input',
          editRequired: true,
          sorter: true,
          editable: true,
          msgtitle:'请输入',
          maxlength: 20,
          // editValidator: phoneAndSolidify,
          editValidator: (value, row, callback) => {
            if (value === undefined || value === '' || value === null) {
              callback(new Error("必填字段"));
            }
            var pattern = /^1[3-9]\d{9}$/;
            var solidify = /^(0\d{2,3}\-)?([2-9]\d{6,7})+(\-\d{1,6})?$/;
            if (pattern.test(value) || solidify.test(value)) {
              callback();
            } else {
              callback(new Error('请输入正确的手机号或固话'));
            }
          }
        },
        {
          title: '备注',
          dataIndex: 'remark',
          filterType: 'input',
          editRequired: false,
          sorter: true,
          msgtitle:'请输入',
          editable: true,
          maxlength: 100,
          rules: []
        },
      ];
    },

    deleteRow(row, index) {
      this.$confirm('确认删除', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$refs.tableInfo.EXECUTE_DELETE([row])
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
    },

    syncFun(details) {
      this.saveData.xxList = details
    },

    addFun() {
      // if (this.saveData.xxList.length == 9) {
      //   this.$notify.warning({ title: '提示信息', message: '地址数量已达到上限' });
      //   return;
      // }
      // this.columns.find(item => item.fieldName === 'provinceId').editItems = pl;
      let p = {
        addressType: '',
        address: '',
        linkMan: '',
        linkPhone: '',
        remark: '',
        provinceId: '',
        cityId: '',
        districtId: ''
      }
      this.$refs.tableInfo.EXECUTE_INSERT(p)
    },
    //初始化市，区
    initRegion(provinceId, cityId) {
      this.initCity(provinceId, false);
      this.initTown(cityId, false);
    },
    //初始化所在省份
    async initProvince() {
      let pl = await this.createRegionList();
      console.log('123', pl)
      this.provinceList = pl;
      this.columns.find(item => item.dataIndex === 'provinceId').editItems = pl;
    },
    //初始化所在市数据
    async initCity(provinceId, flag = true) {
      if (!provinceId || provinceId == null || typeof provinceId == 'undefined') {
        return;
      }
      let city = this.columns.find(item => item.dataIndex === 'cityId');
      let district = this.columns.find(item => item.dataIndex === 'districtId');
      //清空下级数据
      if (flag) {
        city.initialValue = '';
        district.initialValue = '';
        // district.editItems = [];
      }
      //取省数据
      // let rd = this.getRegionData();
      // let cl = this.createSubRegionList(rd[provinceId].children);
      // this.cityList = cl;
    },
    //初始化所在县市数据
    async initTown(cityId, flag = true) {
      if (!cityId || cityId == null || typeof cityId == 'undefined') {
        return;
      }

      let district = this.columns.find(item => item.dataIndex === 'districtId');
      //清空下级数据
      if (flag) {
        district.initialValue = '';
      }
      // let td = this.cityData[cityId].children;
      // let tl = this.createSubRegionList(td);
      //部分城市为县级市，没有县区的下级数据
      // if (tl.length == 0) {
      //   district.rules.required = false;
      //   district.editItems = [];
      //   this.$refs.FormPanel.$refs.form.clearValidate();
      // } else {
      //   district.rules.required = true;
      //   district.editItems = tl;
      // }
    },
  }
};
</script>
